/**
*e 元素
*setting 表格数据头部 var t = {
*								colset:{"colName":"colKey"}
*								readonly:[false,true,,,]
*									}
*isSearch 判断是否为搜索 true or false
*/
function initTable(e,json,setting,isSearch,cells,modifyData){

	    		//----handsontable 初始化 开始------
	        var hotElement = document.querySelector(e);//<====绑定handsontable初始化div 
	        var colHeaders = [];//<===handsontable列头显示值
	        var cols = [];//<====handsontable列头显示值对应的实际字段与其他配置
            var classNames = [];
	        for (var key in setting.colset) {
	            cols.push({ data: setting.colset[key] });
	            colHeaders.push(key);
                classNames.push(setting.colset[key]);
	        }
	        var colwidths = [];
            
	        var hotSettings = {//<====handsontable的配置
	            colHeaders: colHeaders,//当值为true时显示列头，当值为数组时，列头为数组的值
	            data: [],//数据源
	            columns: cols,//列具体配置 
	            // width: 906,
	            autoWrapRow: true,
	             height:400,
	            // maxRows: 22,
	            minRows: 1,
	            filter: false,
	            // currentRowClassName：当前行样式的名称,
	            // currentColClassName：当前列样式的名称,
	            manualColumnResize: true,//当值为true时，允许拖动，当为false时禁止拖动
	            manualRowResize: true,//当值为true时，允许拖动，当为false时禁止拖动
	            stretchH: "all",     //last:延伸最后一列,all:延伸所有列,none默认不延伸。
	            manualColumnMove: true,// 当值为true时，列可拖拽移动到指定列
	            manualRowMove: true,// 当值为true时，行可拖拽至指定行
	            rowHeaders: true, //当值为true时显示行头，当值为数组时，行头为数组的值
	            columnSorting: false,//允许排序
	            sortIndicator: false,
	            contextMenu: false,//显示右键菜单
	            autoColumnSize: true ,//当值为true且列宽未设置时，自适应列大小
	            fixedRowsTop: 1,
   				fixedColumnsLeft: 1,
   				copyable: true,
	            cells:cells != null? cells :function(row, column) {
	            	var cellMeta = {};

				    if(row === 0){
                        cellMeta.type = 'text';
                        cellMeta.readOnly = column == 0;
                        cellMeta.renderer = function(hotInstance, TD, row, col, prop, value) {
                            TD.style.backgroundColor ="#f3f3f3";
                            TD.style.textAlign ="center";
                            TD.textContent = value;
                         cellMeta   
                        }
                    }else{

                        if(column === 0){
                        
                                var isChecked = this.instance.getDataAtCell(this.instance.toVisualRow(row), column);

                                cellMeta.type = 'checkbox';
                                cellMeta.className = 'htCenter' + (isChecked ? ' chked' : '');
                                cellMeta.readOnly = false;
                            
                            

                        }else {
                            cellMeta.type =  'text';
                            //cellMeta.readOnly = true;
                            if(isSearch == true){
                                cellMeta.readOnly = true;
                            }else{
                                cellMeta.readOnly = setting.readOnly[column];
                                cellMeta.className = classNames[column];
                            }   
                        }
                    }
	            	
	            	

	            	return cellMeta;
	            },
               
                modifyData:function(row,col,valueHolder,mode){

                    if(row == 0 && mode == 'set'){
                        var condition = this.getSourceData()[0];
                            var temp = {};
                            var k = classNames[col];
                            for(var key in condition){
                                //if(key == "chk")continue;
                                if(key == k) {
                                    
                                }else{
                                    temp[key] = condition[key];   
                                }
                                
                            }
                            temp[k] = valueHolder.value;
                          //  console.log(temp);

                            hot.fieldFilter(temp);
                    }else{
                       
                    }
                
                }
	        };
	        var hot = new Handsontable(hotElement, hotSettings);

            hot.loadDataNew = function(data,res){
                 if(res == null){
                    data.unshift({chk:"筛选"});
                }else{
                    data.unshift(res);
                }
                    
                hot.loadData(data);
            }
            hot.allData = [];
            for(var i in json ){
                hot.allData.push(json[i]);
            }
             

	        $(e+" .colHeader").click(function(e){

        		if(e.delegateTarget.className.indexOf("cornerHeader")>0)return;

        		var  value = null;
        		for (var key in setting.colset) {
		            if(key == e.target.innerText){
		            	value = setting.colset[key];
		            	break;
		            }
	        	}
	        	if(value == 'chk'){
	        		var datas = hot.getSourceData();
                    for(var i in datas){
                        if(i== 0)continue;
                        var d = datas[i];
                        d.chk = !d.chk;
                    }
                   // console.log(hot);
                    hot.loadData(datas);
	        		return;
	        	}
	        	
	        });
           


	        ///字段筛选
	        /*
       		 *key 筛选的字段
       		 *value 筛选的字段的值
       		 *
       		 */
	        hot.fieldFilter=function(condition){
        	
	        	var datas = hot.allData;
               // condition = datas[0];
	        	var tmp = [];
                isAll = true;
                for(var i in condition){
                    var val = condition[i];
                    if(i== "chk")continue;
                    if(val != undefined && val !="" ) isAll = false;

                }
	        	for(var i in datas){
                    
	        		var d = datas[i];
	        		
                    var isMatch = true;
                    if(isAll){
                        tmp.push(d);
                    }else{
                       for(var j in condition){
                            if(j == "chk")continue;

                           
                                var name =d[j];
                               
                               if(name == undefined || name=="" ){
                                    isMatch = false
                                }else{
                                    if(condition[j] == ""){
                                        isMatch = true && isMatch;
                                    }else if(isNumber(name)){
                                        isMatch = (name == condition[j]) && isMatch;
                                    }else{
                                        isMatch = (name.indexOf(condition[j])>=0) && isMatch
                                    }
                                    
                                }
                            

                           
                        }

                        if(isMatch)tmp.push(d); 
                    }
                    
	        	}
	        	//console.log(tmp);
	        	this.loadDataNew(tmp,condition);
        	
       		 }

       		 ///从其他数据源 选择数据
       		 /*
       		 *data 其他数据源
       		 *toData 上级数据源
       		 *
       		 */
       		hot.addOutData =function(data,toData,searchSet,key){
        		layer.open({
				  type: 1,
				  title: false,
				  closeBtn: 0,
				  area: ['1000px', '400px'],
				  skin: 'layui-layer-rim',
				  shadeClose: true,
				  btn:['确定选择','取消'],
				  content: '<html><div style="text-align:center"><input type="button" value="显示全部" class="btn" onclick="hot.searchHot.lookAll(hot.searchData)"/></div><div id="addOutData" ></div></html>',
				  success: function(layero, index){
                        var s = set;
				   	    if(searchSet != null) s = searchSet
					    var hot1 = initTable("#addOutData",data,s,true);
					    hot1.loadData(data);
                        hot.searchData = data;
                        hot.searchHot = hot1;

					  },
					yes:function(index, layero){
				   
				   for(var i in hot.searchData){
				   	  var d = data[i];
				   	  if(d.chk == true && !contains(toData,d,key)){
				   	  	d.chk = false;
                       //console.log(d);
				   	  	toData.push(d);
				   	  }
				   }
                        hot.allData = [];
                        for(var i in toData ){
                            hot.allData.push(toData[i]);
                        }
				   		hot.loadData(toData);

				   		layer.closeAll();
                        


					},
					btn2:function(index, layero){
						layer.closeAll();
                        
					
					},
                    end:function(){
                       hot.searchData = null;
                        hot.searchHot = null; 
                    }		  
				});
  
        	
        	}
	        /*
	        *显示全部数据
	        */
	        hot.lookAll =function(data){
        	 	hot.loadData(data);
	        }
	        /*
	        *删除选中
	        */
	        hot.deleteSelect = function(data){
	        	
	        	if(data.length > 0){
	        		for (var i = data.length - 1; i >= 0; i--) {

	        			    var d = data[i];
	        		     if(d.chk == true)data.splice(i,1);
	        			
	        		}
	        	}
	        	
	        	hot.loadData(data);
	        }
            hot.loadDataNew(json);
           
            /*
            for(var key in colHeaders){
                colwidths.push(hot.getColWidth(key));
            }

            var hotHeaderSettings = {
                colHeaders: false,//当值为true时显示列头，当值为数组时，列头为数组的值
                data: [],//数据源
                columns: cols,//列具体配置 
                // width: 906
                autoWrapRow: true,
                height:30,
                // maxRows: 22,
                minRows: 1,
                filter: false,
                colWidths:colwidths,
                // currentRowClassName：当前行样式的名称,
                // currentColClassName：当前列样式的名称,
                manualColumnResize: true,//当值为true时，允许拖动，当为false时禁止拖动
                manualRowResize: true,//当值为true时，允许拖动，当为false时禁止拖动
                stretchH: "all",     //last:延伸最后一列,all:延伸所有列,none默认不延伸。
                manualColumnMove: true,// 当值为true时，列可拖拽移动到指定列
                manualRowMove: true,// 当值为true时，行可拖拽至指定行
                rowHeaders: true, //当值为true时显示行头，当值为数组时，行头为数组的值
                columnSorting: false,//允许排序
                sortIndicator: false,
                contextMenu: false,//显示右键菜单
                autoColumnSize: true ,//当值为true且列宽未设置时，自适应列大小
                 fixedRowsTop: 1,
                 fixedColumnsLeft: 1,
                 copyable: true,
                 cells:function(row,col){
                    var cellMeta = {};
                    if(col === 0){
                        cellMeta.readOnly = true;
                    }
                    return cellMeta;
                 },
                 modifyData:function(row,col,valueHolder,mode){
                    if(mode == 'set'){
                       // console.log(valueHolder);
                        var condition = hotheader.getSourceData()[0];
                        var temp = {};
                        var k = classNames[col];
                        for(var key in condition){
                            if(key == "chk")continue;
                            if(key == k) {
                                
                            }else{
                                temp[key] = condition[key];   
                            }
                            
                        }
                        temp[k] = valueHolder.value;
                        console.log(temp);

                        hot.fieldFilter(temp);
                    }
                 }

            }
             
            var hotheader = new Handsontable(document.querySelector(e+"_header"), hotHeaderSettings);

             hot.addHook('modifyRowHeaderWidth',function(rowHeaderWidth){
                
                
                
            });
             hotheader.loadData([{chk:"筛选"}]);

            */
              
	        /*
	        *反选 或取消反选
	        *
	       
	        hot.selectAll =function(){
	        	var data = hot.getSourceData();
	        	for(var i in data){
	        		var d = data[i];
	        		d.chk = !d.chk;
	        	}
	        } */
	        return hot ;
    	}


        //----工具类 开始----
        var utl = {};
        
       
        
        utl.Binary = {
            fixdata(data) { //文件流转BinaryString
                var o = "",
                    l = 0,
                    w = 10240;
                for (; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
                o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
                return o;
            },
            s2ab(s) { //字符串转字符流
                var buf = new ArrayBuffer(s.length);
                var view = new Uint8Array(buf);
                for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
                return buf;
            }
        }
        utl.XLSX = {
            wb: null,
            rABS: false,
            import(f, c) {//导入根据文件
                this.wb = null;
                var reader = new FileReader();
                reader.onload = function (e) {
                    var data = e.target.result;
                    if (utl.XLSX.rABS) {
                        utl.XLSX.wb = XLSX.read(btoa(utl.Binary.fixdata(data)), {//手动转化
                            type: 'base64'
                        });
                    } else {
                        utl.XLSX.wb = XLSX.read(data, {
                            type: 'binary'
                        });
                    }
                    if (c && typeof (c)) {
                        c();
                    }
                };
                if (utl.XLSX.rABS) {
                    reader.readAsArrayBuffer(f);
                } else {
                    reader.readAsBinaryString(f);
                }
            },
            onImport(obj, c) {//导入根据 input file标签
                if (!obj.files) {
                    return;
                }
                this.import(obj.files[0], c);
            },
            getSheetsByIndex(index = 0) {//获取数据根据Sheets索引
                return XLSX.utils.sheet_to_json(this.wb.Sheets[this.wb.SheetNames[index]]);
            },
            getCharCol(n) {
                var temCol = '',
                    s = '',
                    m = 0
                while (n > 0) {
                    m = n % 26 + 1
                    s = String.fromCharCode(m + 64) + s
                    n = (n - m) / 26
                }
                return s
            },
            export(json, title, type) {//导出
                var keyMap = [];//获取keys
                for (k in json[0]) {
                    keyMap.push(k);
                }
                var tmpdata = [];//用来保存转换好的json 
                json.map((v, i) => keyMap.map((k, j) => Object.assign({}, {
                    v: v[k],
                    position: (j > 25 ? utl.XLSX.getCharCol(j) : String.fromCharCode(65 + j)) + (i + 1)
                }))).reduce((prev, next) => prev.concat(next)).forEach((v, i) => tmpdata[v.position] = {
                    v: v.v
                });
                var outputPos = Object.keys(tmpdata); //设置区域,比如表格从A1到D10
                var tmpWB = new Object();
                title = title ? title : "mySheet";
                tmpWB.SheetNames = [title];
                tmpWB.Sheets = {};
                tmpWB.Sheets[title] = Object.assign({}, tmpdata, //内容
                    {
                        '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] //设置填充区域
                    });
                return new Blob([utl.Binary.s2ab(XLSX.write(tmpWB,
                    { bookType: (type == undefined ? 'xlsx' : type), bookSST: false, type: 'binary' }//这里的数据是用来定义导出的格式类型
                ))], { type: "" }); //创建二进制对象写入转换好的字节流
            },
            onExport(json, title, type) {//直接下载
                utl.Download.byObj(this.export(json, title, type), "下载.xlsx");
            }
        };
        utl.Download = {
            byURL(url, fileName) {//动态下载
                var tmpa = document.createElement("a");
                tmpa.download = fileName || "下载";
                tmpa.href = url; //绑定a标签
                tmpa.click(); //模拟点击实现下载
            },
            byObj(obj, fileName) {//内存二进制数据下载
                this.byURL(URL.createObjectURL(obj), fileName);
                setTimeout(function () { //延时释放
                    URL.revokeObjectURL(obj); //用URL.revokeObjectURL()来释放这个object URL
                }, 100);
            }
        }
        utl.Object = {
            reverse(obj) {//对象键值倒转
                var o = new Object();
                for (var k in obj) {
                    o[obj[k]] = k;
                }
                return o;
            },
            deepCopy() {//深拷贝
                var temp = obj.constructor === Array ? [] : {}
                for (var val in obj) {
                    temp[val] = typeof obj[val] == 'object' ? deepCopy(obj[val]) : obj[val];
                }
                return temp;
            },
            copyJson(o) { return JSON.parse(JSON.stringify(o)); }//拷贝JSON格式
        }
        //----工具类 结束----
  
        function contains(arr ,obj ,key){
            for(var i in arr){
                var t = arr[i];
                if(t[key] == obj[key])return true;
            }
            return false;
        }
        function isNumber(obj) {  
            return !isNaN(parseFloat(obj)) && isFinite(obj);  
        }  
    	 //------导入导出 excel-----
    	/*
    	* emt 元素 
    	**/
        function imptExcel(emt) {//<===导入
            utl.XLSX.onImport(emt, function () {
                var rt = utl.XLSX.getSheetsByIndex();//<===默认获取Sheet1
                var tmp = [];
                rt.forEach(function (value, index, array) {
                    var t = new Object();
                    for (var k in value) {
                        t[colset[k]] = value[k];
                    }
                    tmp.push(t);
                });
                cookie = tmp;
                hot.loadData(tmp);//<====将读取完成数据显示到handsontable
            	//console.log(tmp);
                		
                        

            });
        }
        
        /*
        * 导出excel
        */
        function downExcel() {//<===下载导出数据
            var d = utl.Object.copyJson(hot.getSourceData());//<=====读取handsontable的数据
            d.unshift(utl.Object.reverse(colset));//<====追加到列头
            utl.XLSX.onExport(d);//<====导出
        }
        /*
        *
        *查看json数据
        *k0 是否保留第0 行 true 从0 开始 fasle: 从1开始
        */
        function showJSONData(data,k0) {//<====获取真实数据
            var tmp = [];
            data.forEach(function (value, index, array) {
                if(k0 == false && index == 0)return;
                var t = new Object();
                for (var k in value) {

                    t[k] =  value[k];//<====将xlsx数据转为实际需要的值
                }
                tmp.push(t);
            });

            /*
            *更多规则自己定义吧
            */
            //alert(JSON.stringify(tmp));
           // window.open("data:text/html;charset=utf-8,"+JSON.stringify(tmp));
           // console.log(tmp);
            return JSON.stringify(tmp);
        }
        